﻿using UnityEngine;
using System.Collections;

public class PhysWind : MonoBehaviour {

	public bool windEnable = true;
	public float wind = 1.0f;
	public float windAng = 0.05f;
	public float windChaos = 2.0f;
	public float windZoneSize = 10.0f;
	public Rigidbody body;
	public float density = 1;

	void FixedUpdate() {

		if (body == null) body = gameObject.GetComponentInParent<Rigidbody>();
		if (body == null) return;

		if (windEnable && wind != 0) {

			
			float windForceX = 0;
			float windForceZ = 0;
			Vector3 torque = new Vector3 (0, 0, 0);


			float t = (Time.realtimeSinceStartup);
			t *= windChaos;
			t += Mathf.Cos (2*Mathf.PI*transform.position.x/windZoneSize)*2;
			t += Mathf.Sin (2*Mathf.PI*transform.position.z/windZoneSize)*2;
			t *= 2*Mathf.PI;
			float wind1 = Mathf.Cos (t / 7);
			wind1 +=      Mathf.Cos (t / 27);
			float wind2 = Mathf.Cos (t / 11);
			wind2 +=      Mathf.Cos (t / 4 );
			float wind3 = Mathf.Cos (t / 21);
			wind3 +=      Mathf.Cos (t / 31);

			body.SetDensity(density);
			float size = body.mass / density;

			size = Mathf.Pow(size, 2.0f/3.0f);

			
			torque = new Vector3 (windAng * size * wind1,
			                                          windAng * size * wind2,
			                                          windAng * size * wind3);

			windForceX = wind * (wind1 + wind2/2) * size;
			windForceZ = wind * (wind3 + wind2/2) * size;

			float wind4 = (Time.realtimeSinceStartup * 6.28f / 23 * windChaos);
			Vector3 force = Quaternion.Euler(0, wind4, 0) * new Vector3 (windForceX, 0, windForceZ);
			
			body.AddForce (force, ForceMode.Impulse);			
			body.AddTorque (torque, ForceMode.Impulse);


		}



	}
}
